Page({
  data: {
    currentLocation: {
      latitude: '',
      longitude: '',
      address: '',
      updated_at: ''
    },
    serviceAreas: [],
    locationHistory: [],
    showAddAreaModal: false,
    newArea: {
      name: '',
      latitude: '',
      longitude: '',
      radius: 5
    }
  },

  onLoad: function() {
    this.loadLocationData();
  },

  loadLocationData: function() {
    this.loadCurrentLocation();
    this.loadServiceAreas();
    this.loadLocationHistory();
  },

  loadCurrentLocation: function() {
    const locationUtils = require('../../utils/location.js');
    
    locationUtils.getTechnicianLocation()
      .then((data) => {
        this.setData({
          'currentLocation.latitude': data.latitude,
          'currentLocation.longitude': data.longitude,
          'currentLocation.address': data.address || '',
          'currentLocation.updated_at': data.updated_at
        });
      })
      .catch((error) => {
        console.log('获取当前位置失败:', error);
      });
  },

  refreshLocation: function() {
    const locationUtils = require('../../utils/location.js');
    
    locationUtils.getCurrentLocation()
      .then((location) => {
        this.setData({
          'newArea.latitude': location.latitude,
          'newArea.longitude': location.longitude
        });
        
        // 同时更新当前页面显示的位置
        this.setData({
          'currentLocation.latitude': location.latitude,
          'currentLocation.longitude': location.longitude
        });
      })
      .catch((error) => {
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
      });
  },

  updateCurrentLocation: function() {
    const locationUtils = require('../../utils/location.js');
    
    // 如果没有手动输入坐标，使用当前获取的位置
    let latitude = this.data.newArea.latitude || this.data.currentLocation.latitude;
    let longitude = this.data.newArea.longitude || this.data.currentLocation.longitude;
    
    if (!latitude || !longitude) {
      wx.showToast({
        title: '请先获取或输入位置坐标',
        icon: 'none'
      });
      return;
    }
    
    locationUtils.updateTechnicianLocation(latitude, longitude)
      .then((data) => {
        wx.showToast({
          title: '位置更新成功',
          icon: 'success'
        });
        
        this.setData({
          'currentLocation.latitude': data.latitude,
          'currentLocation.longitude': data.longitude,
          'currentLocation.updated_at': data.updated_at
        });
      })
      .catch((error) => {
        wx.showToast({
          title: '位置更新失败',
          icon: 'none'
        });
      });
  },

  loadServiceAreas: function() {
    const locationUtils = require('../../utils/location.js');
    
    locationUtils.getServiceAreas()
      .then((data) => {
        this.setData({
          serviceAreas: data
        });
      })
      .catch((error) => {
        console.log('获取服务区域失败:', error);
      });
  },

  showAddAreaModal: function() {
    this.setData({
      showAddAreaModal: true
    });
  },

  hideAddAreaModal: function() {
    this.setData({
      showAddAreaModal: false,
      newArea: {
        name: '',
        latitude: '',
        longitude: '',
        radius: 5
      }
    });
  },

  onAreaNameChange: function(e) {
    this.setData({
      'newArea.name': e.detail.value
    });
  },

  onAreaRadiusChange: function(e) {
    this.setData({
      'newArea.radius': e.detail.value
    });
  },

  onAreaLatitudeChange: function(e) {
    this.setData({
      'newArea.latitude': e.detail.value
    });
  },

  onAreaLongitudeChange: function(e) {
    this.setData({
      'newArea.longitude': e.detail.value
    });
  },

  saveServiceArea: function() {
    if (!this.data.newArea.name) {
      wx.showToast({
        title: '请输入区域名称',
        icon: 'none'
      });
      return;
    }

    if (!this.data.newArea.latitude || !this.data.newArea.longitude) {
      wx.showToast({
        title: '请输入坐标',
        icon: 'none'
      });
      return;
    }

    const locationUtils = require('../../utils/location.js');
    
    locationUtils.addServiceArea(
      this.data.newArea.name,
      this.data.newArea.latitude,
      this.data.newArea.longitude,
      this.data.newArea.radius
    )
      .then((data) => {
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        });
        
        this.hideAddAreaModal();
        this.loadServiceAreas(); // 重新加载服务区域列表
      })
      .catch((error) => {
        wx.showToast({
          title: '添加失败',
          icon: 'none'
        });
      });
  },

  deleteServiceArea: function(e) {
    const areaId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个服务区域吗？',
      success: (res) => {
        if (res.confirm) {
          const locationUtils = require('../../utils/location.js');
          
          locationUtils.deleteServiceArea(areaId)
            .then(() => {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              this.loadServiceAreas(); // 重新加载服务区域列表
            })
            .catch((error) => {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
            });
        }
      }
    });
  },

  loadLocationHistory: function() {
    // 这里可以调用后端API获取位置历史记录
    // 暂时使用模拟数据
    const history = [
      {
        id: 1,
        created_at: '2023-05-15 10:30:25',
        latitude: '39.9042',
        longitude: '116.4074'
      },
      {
        id: 2,
        created_at: '2023-05-15 09:15:30',
        latitude: '39.9050',
        longitude: '116.4080'
      }
    ];
    
    this.setData({
      locationHistory: history
    });
  }
})